import { useEffect, useState } from "react";
import { arrange, pageStaffClass } from "../api";
import { monthFirstDay, monthLastDay, weekFirstDay, weekLastDay } from "@/utils/date";
import { Button, DatePicker, Pagination, Radio, Space, Table, TimePicker, Tooltip, Select } from "antd";
import { LayoutOutlined, LeftOutlined, RightOutlined } from "@ant-design/icons";
import { page as pageStaff } from '@/views/employee/staff/api';
import { useFormDialog } from "@/hooks/useForm";
import dayjs from "dayjs";
import { buildArrangeModel } from "../data";
import FormModal from "@/component/FormModal";
import StaffDetail from "./StaffDetail";

const StaffView = ({ callback }) => {
    // 右上角 周 月 切换
    const [position, setPosition] = useState('week');
    // 表格
    const [columns, setColumns] = useState([]);
    const [data, setData] = useState([]);
    // 表格滚动
    const [scroll, setScroll] = useState({ x: undefined });
    // 上一周/上一月
    const [prev, setPrev] = useState('上一周');
    // 下一周/下一月
    const [next, setNext] = useState('下一周');
    // 日历切换的日期
    const [date, setDate] = useState(dayjs());
    // 新增: 存储选中单元格详情
    const [selectedCell, setSelectedCell] = useState(null);

    const [pagination, setPagination] = useState({
        current: 1,
        size: 10,
        total: 0,
    });

    /**
     * 月/周 切换
     */
    const onChangeDate = (val) => {
        setPosition(val);
        if (val === 'week') {
            setPrev('上一周');
            setNext('下一周');
        } else {
            setPrev('上一月');
            setNext('下一月');
        }
    }

    // 上一周/上一月  下一周/下一月
    const onNextDate = (operator) => {
        let datetime = date;
        if (operator === 'prev') {
            datetime = dayjs(datetime).add(-1, position);
        } else {
            datetime = dayjs(datetime).add(1, position);
        }
        setDate(datetime);
    }

    /**
     * 表头解析
     * TODO 添加搜索
     */
    const tableColumns = (val) => {
        let columns = [
            {
                title: '#',
                key: 'index',
                width: 50,
                align: 'center',
                fixed: 'left',
                render: (val, record, index) => {
                    return index + 1;
                }
            },
        ];

        val.forEach(each => {
            columns.push({
                title: each.label,
                dataIndex: each.field,
                width: 100,
                key: each.field,
                ellipsis: true,
                fixed: each.fixed,
                onCell: (record, index) => onTableCell(each, record, index),
            });
        });
        setColumns(columns);
    }

    // 单元格事件
    const onTableCell = (column, record, index) => ({
        onMouseEnter: (event) => {
            // 鼠标进入时改变样式
            event.target.style.backgroundColor = '#e7effcff';
            event.target.style.cursor = 'pointer';
        },
        onMouseLeave: (event) => {
            // 鼠标离开时恢复样式
            event.target.style.backgroundColor = '';
            event.target.style.cursor = 'default';
        },
        onClick: () => onCellClickHandler(column, record, index),
    });

    const onCellClickHandler = (column, record, index) => {
        if (column.field !== 'code' && column.field !== 'name' && column.field !== '#') {
            // 新增: 存储选中单元格信息到状态
            let event = {
                staffId: record.id,
                staffName: record.name,
                staffCode: record.code,
                date: column.field,
            }
            setSelectedCell(event);

            // 临时排班
            if (!record[column.field]) {
                onOpenTemporaryDialog(event);
            }
        }
    }

    const onOpenTemporaryDialog = (event) => {
        let work_date = dayjs(event.date, 'YYYY-MM-DD');
        let work_time = dayjs(new Date());
        setEmployeeOptions([{
            label: event.staffName,
            value: event.staffId,
        }]);

        let model = {
            id: event.id,
            name: event.title,
            color: event.backgroundColor,
            remark: event.remark,
            workDate: [work_date, work_date],
            workTime: [work_time, work_time.add(30, 'm')],
            staffIds: [event.staffId],
        }
        temporaryFormModal.isOpenDialog(model);
    }



    // -------------------
    // --- 临时排班表单 ---
    // -------------------

    // 员工下拉多选
    const [employeeOptions, setEmployeeOptions] = useState([]);
    const onSearchEmployeeHandler = (val) => {
        let query = {
            params: [
                { field: 'name', expr: 'LIKE_LEFT', value: val },
            ]
        };
        pageStaff(query).then(resp => {
            let options = resp?.data?.records.map(item => ({
                label: item.name,
                value: item.id,
            }));
            setEmployeeOptions(options);
        });
    }

    // 表单提交回调
    const onTemporaryCallback = (model) => {
        let params = {
            type: 'temporary',
            data: buildArrangeModel(model),
        };

        temporaryFormModal.onSubmit(params, onReloadHandler);
    }

    const temporaryFormModal = useFormDialog({
        title: '临时排班',
        width: 450,
        save: arrange,
        callback: onTemporaryCallback,
        items: [
            {
                label: '名称',
                name: 'name',
                rules: [{ required: true, message: '请输入名称' }],
            },
            {
                label: '颜色',
                name: 'color',
            },
            {

                label: '日期',
                name: 'workDate',
                rules: [{ required: true, message: '请选择日期' }],
                render: <DatePicker.RangePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
            },
            {
                label: '时间',
                name: 'workTime',
                rules: [{ required: true, message: '请选择时间' }],
                render: <TimePicker.RangePicker changeOnScroll needConfirm={false} format="HH:mm" style={{ width: '100%' }} />,
            },
            {
                label: '员工',
                name: 'staffIds',
                rules: [{ required: true, message: '请选择员工' }],
                render: <Select
                    mode="multiple"
                    showSearch
                    allowClear
                    placeholder="请选择员工"
                    optionFilterProp="label"
                    filterOption={false}
                    onSearch={(val) => onSearchEmployeeHandler(val)}
                    options={employeeOptions}
                />
            },
        ],
    });

    /**
     * 加载列表数据
     */
    const onReloadHandler = () => {
        let query = {
            params: {
                start: position === 'week' ? weekFirstDay(date).format('YYYY-MM-DD') : monthFirstDay(date).format('YYYY-MM-DD'),
                end: position === 'week' ? weekLastDay(date).format('YYYY-MM-DD') : monthLastDay(date).format('YYYY-MM-DD'),
            },
            data: getQuery(),
        };
        pageStaffClass(query).then(resp => {
            let result = resp?.data;
            if (result) {
                // 表头
                tableColumns(result.headers);
                setData(result.data.records);
                setPagination({
                    current: result.data.pageNo,
                    size: result.data.pageSize,
                    total: result.data.total,
                });
                position === 'week' ? setScroll({ x: 800 }) : setScroll({ x: 3000 });
            }
        });
    }

    const getQuery = () => {
        return {};
    }

    const onChangeView = () => {
        callback();
    }

    useEffect(() => {
        onReloadHandler();
    }, [position, date]);

    return (
        <div style={{ display: 'flex', height: 'calc(100vh - 140px)' }} >
            {/* 左侧表格区 */}
            <div style={{ width: '78%' }}>
                {/* 工具栏 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    padding: 8,
                }}>
                    {/* 左侧工具栏 */}
                    <Space>
                        <Tooltip title="日历视图">
                            <Button
                                onClick={onChangeView}
                                icon={<LayoutOutlined style={{ color: '#1890ff' }} />}
                                color="primary"
                                variant="filled"
                                style={{ borderRadius: 4, marginRight: 10 }}
                            />
                        </Tooltip>
                        <Tooltip title={prev}>
                            <Button
                                size="small"
                                shape="circle"
                                icon={<LeftOutlined style={{ color: '#1890ff' }} />}
                                onClick={() => onNextDate('prev')}
                                color="default" variant="outlined"
                            />
                        </Tooltip>
                        <Tooltip title={next}>
                            <Button
                                size="small"
                                shape="circle"
                                icon={<RightOutlined style={{ color: '#1890ff' }} />}
                                onClick={() => onNextDate('next')}
                                color="default" variant="outlined"
                            />
                        </Tooltip>
                    </Space>

                    {/* 右侧操作按钮 */}
                    <Space>
                        <Radio.Group value={position} onChange={e => onChangeDate(e.target.value)}>
                            <Radio.Button value="month" style={{ paddingInline: 8 }}>月</Radio.Button>
                            <Radio.Button value="week" style={{ paddingInline: 8 }}>周</Radio.Button>
                        </Radio.Group>
                    </Space>
                </div>
                {/* 表格 */}
                <div style={{ padding: 8 }}>
                    <Table
                        bordered
                        rowKey="id"
                        size='small'
                        columns={columns}
                        dataSource={data}
                        pagination={false}
                        scroll={scroll}
                        style={{ marginBottom: '16px' }}
                    />

                    <Pagination
                        align="end"
                        showSizeChanger
                        showQuickJumper
                        total={pagination.total}
                        pageSize={pagination.size}
                        current={pagination.current}
                        pageSizeOptions={[10, 20, 50]}
                        onChange={onReloadHandler}
                        showTotal={total => `共 ${total} 条`}
                        style={{
                            marginTop: '16px',
                        }}
                    />
                </div>
                {/* 表单 */}
                <FormModal props={temporaryFormModal} />
            </div>

            {/* 右侧详情区域 */}
            <StaffDetail cell={selectedCell} callback={onOpenTemporaryDialog} />

            {/* <div style={{ width: '20%', border: '1px solid #e8e8e8', borderRadius: 8, padding: 8, overflow: 'auto' }}>
                {selectedCell ? (
                    <div className="detail-panel">
                        <h3 style={{ marginBottom: '16px', paddingBottom: '8px', borderBottom: '1px solid #e8e8e8' }}>
                            事件详情
                        </h3>
                        <div style={{ display: 'grid', gap: '12px' }}>
                            <div>
                                <span style={{ color: '#666', display: 'inline-block', width: '80px' }}>行索引:</span>
                                <span>{selectedCell.index}</span>
                            </div>
                            <div>
                                <span style={{ color: '#666', display: 'inline-block', width: '80px' }}>员工姓名:</span>
                                <span>{selectedCell.record.name}</span>
                            </div>
                            <div>
                                <span style={{ color: '#666', display: 'inline-block', width: '80px' }}>日期:</span>
                                <span>{dayjs(selectedCell.column.field).format('YYYY-MM-DD')}</span>
                            </div>
                            <div>
                                <span style={{ color: '#666', display: 'inline-block', width: '80px' }}>单元格值:</span>
                                <span>{selectedCell.record[selectedCell.column.field] || '-'}</span>
                            </div>
                        </div>
                    </div>
                ) : (
                    <div style={{ textAlign: 'center', color: '#999', padding: '40px 0' }}>
                        <p>点击表格单元格查看详情</p>
                    </div>
                )}
            </div> */}
        </div>
    );
}

export default StaffView;